<template>
  <div>
    <Category :scene="scene" />
    <el-card style="margin: 10px 0px">
      <div v-show="scene == 0">
        <el-button
          v-has="`btn.Attr.add`"
          type="primary"
          size="default"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addAttr"
        >
          添加属性
        </el-button>
        <el-table border style="margin: 10px 0px" :data="attrArr">
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="150"
            align="center"
            prop="attrName"
          >
          </el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">
              <el-tag
                v-for="(item, index) in row.attrValueList"
                :key="item.id"
                type="primary"
                style="margin-right: 5px"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row, $index }">
              <el-button
                v-has="`btn.Attr.update`"
                type="primary"
                size="small"
                icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-popconfirm
                :title="`确定要删除${row.attrName}吗?`"
                width="200px"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    v-has="`btn.Attr.remove`"
                    type="danger"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input v-model="attrParams.attrName" placeholder="请输入属性名称"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="attrParams.attrName ? false : true"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button size="default" @click="cancel">
          取消
        </el-button>
        <el-table border style="margin: 10px 0px" :data="attrParams.attrValueList">
          <el-table-column
            width="80px"
            type="index"
            align="center"
            label="序号"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">
              <el-input
                v-if="row.flag"
                ref="input"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                size="small"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="toEdit(row)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作" width="300px" align="center">
            <template #default="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          @click="save"
        >
          保存
        </el-button>
        <el-button size="default" @click="cancel">
          取消
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import useCategoryStore from '@/store/modules/category'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import type { AttrResponseData, AttrList, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'

const categoryStore = useCategoryStore()
//存储已有的属性和属性值
const attrArr = ref<AttrList>([])
//收集新增的属性的数据
const attrParams = reactive<Attr>({
  attrName: '',
  categoryId: '',
  categoryLevel: 3,
  attrValueList: []
})
//控制卡片切换
const scene = ref<number>(0) //scene=0时展示table;scene=1时展示添加与修改属性的结构;

const input = ref()

//获取已有的属性和属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore

  const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code == 200) {
    attrArr.value = result.data
  }
}

//监听仓库三级分类id的变化
watch(
  () => categoryStore.c3Id,
  () => {
    //清空上一次查询的属性和属性值
    attrArr.value = []
    //确保三级分类ID有了之后再发请求
    if (!categoryStore.c3Id) return
    //获取分类ID
    getAttr()
  }
)

//添加属性按钮
const addAttr = () => {
  //先清空数据
  Object.assign(attrParams, {
    attrName: '',
    categoryId: '',
    categoryLevel: 3,
    attrValueList: []
  })

  scene.value = 1
  attrParams.categoryId = categoryStore.c3Id
}

//table表格修改按钮
const updateAttr = (row: Attr) => {
  scene.value = 1
  //初始化数据--需要用到深拷贝
  // Object.assign(attrParams, row) //这里用到的是浅拷贝，有坑
  Object.assign(attrParams, JSON.parse(JSON.stringify(row))) //利用JSON序列化反序列化实现深拷贝
}

//取消按钮
const cancel = () => {
  scene.value = 0
}

//添加属性值按钮
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true
  })
  //input自动获取焦点
  nextTick(() => {
    input.value.focus()
  })
}
//保存按钮
const save = async () => {
  //保存之前先验证attrParams是否合法
  if (attrParams.attrName.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性名称不能为空！'
    })
    return
  }
  if (attrParams.attrValueList.length < 1) {
    ElMessage({
      type: 'error',
      message: '必须有属性值！'
    })
    return
  }

  // 发送请求
  const result: any = await reqAddOrUpdateAttr(attrParams)
  if (result.code == 200) {
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功'
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败'
    })
  }
}

// 属性值表单元素失去焦点的方法
const toLook = (row: AttrValue, $index: number) => {
  //非法情况1：不能为空
  if (row.valueName.trim() == '') {
    // 删除属性值为空的
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能为空'
    })
    return
  }
  //非法情况2：不能出现重复
  const repeat = attrParams.attrValueList.find((item) => {
    // 切记把当前失去焦点的属性值对象从数组中扣出去之后再判断
    if (item != row) {
      return item.valueName == row.valueName
    }
  })

  if (repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复'
    })
    return
  }

  row.flag = false
}

//点击变成编辑模式
const toEdit = (row: AttrValue) => {
  row.flag = true
  //input自动获取焦点
  nextTick(() => {
    input.value.focus()
  })
}

//删除某一个已有属性的按钮
const deleteAttr = async (attrId: number) => {
  const result: any = await reqRemoveAttr(attrId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败'
    })
  }
}
</script>

<style lang="scss" scoped></style>
